package com.ruben.utils;
/**
 * @ClassName: SpringContextHolder
 * @Date: 2020/11/12 0012 20:40
 * @Description:
 */

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @ClassName: SpringContextHolder
 * @Description: 我还没有写描述
 * @Date: 2020/11/12 0012 20:40
 * *
 * @author: <achao1441470436@gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
@Lazy(false)
@Component("SpringContextHolder")
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static final String ERROR_MESSAGE = "applicationContext尚未注入";
    private static ApplicationContext applicationContext;

    public static <T> T getBean(Class<T> type) {
        return Optional.ofNullable(applicationContext).map(context -> context.getBean(type)).orElseThrow(() -> new IllegalStateException(ERROR_MESSAGE));
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) Optional.ofNullable(applicationContext).map(context -> context.getBean(name)).orElseThrow(() -> new IllegalStateException(ERROR_MESSAGE));
    }

    @Override
    public void destroy() {
        applicationContext = null;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return Optional.ofNullable(applicationContext).orElseThrow(() -> new IllegalStateException(ERROR_MESSAGE));
    }


}
